<?php
namespace app\common\traits\wechat;


use Thenbsp\Wechat\Message\Template\Sender;
use Thenbsp\Wechat\Message\Template\Template;
use think\Log;

trait WechatTemplateMessage
{
    use WechatAccessToken;

    /**
     * 充值成功模板消息提醒
     * @param $data['userProjetId'] 用户加入计划id
     * @param $data['userNames'] 用户名称
     * @param $data['projetName'] 计划名称
     * @param $data['openid'] 微信openid
     * @param $data['orderNo'] 订单号
     * @return bool|string
     */
    public function topUpBalancePrompt($data)
    {
        $blance = formatAmount(model('UserProjetFundsLog')->getFieldUserProjetFundsLog(['userProjetId'=>$data['userProjetId'], 'state'=>1], 'sum(changeAmount)'));
        $content = "余额充值成功，此消息为您的凭证。您也可以登录“我的互助”查看凭证。\n";
        //微信模板提示
        $template = new Template(config('wechat_template.WechatTemplateMessageJoin'));

        // 模板参数，每一个模板 ID 都对应一组参数
        $template
            ->add('first',      $content)
            ->add('keyword1',   $data['userNames'])
            ->add('keyword2',   $data['projetName'])
            ->add('keyword3',   $blance . '元')
            ->add('remark',     "\n点击下方详情，去“我的互助”查看凭证", '#0000ff');
// 跳转链接
        $template->setUrl(config('domain.domain') .url('user/projet'));
// 发给谁
        $template->setOpenid($data['openid']);

        $sender = new Sender($this->getAccessTokenObject());
        try {
            $msgid = $sender->send($template);
        } catch (\Exception $e) {
            Log::info('互助单号:'.$data['orderNo'].'，'.$e->getMessage());
            return $e->getMessage();
        }
    }

    /**
     * 加入计划模板消息提醒
     * @param $data['userNames'] 用户名称
     * @param $data['projetName'] 计划名称
     * @param $data['createTime'] 加入时间
     * @param $data['totalAmount'] 支付总金额
     * @param $data['openid'] 微信openid
     * @param $data['orderNo'] 订单号
     * @return bool|string
     */
    public function joinPlanPrompt($data)
    {
        $content = $data['userNames'] . '已经成功加入' . $data['projetName'] . "，此消息为您的凭证。您也可以登录“我的互助”查看凭证。\n";
        //微信模板提示
        $template = new Template(config('wechat_template.WechatTemplateMessageRecharge'));

        // 模板参数，每一个模板 ID 都对应一组参数
        $template
            ->add('first',      $content)
            ->add('keyword2',   date('Y年m月d日', $data['createTime']))
            ->add('keyword1',   formatAmount($data['totalAmount']) . '元')
            ->add('remark',     "\n点击下方详情，去“我的互助”查看凭证", '#0000ff');
        // 跳转链接
        $template->setUrl(config('domain.domain') .url('user/projet'));
        // 发给谁
        $template->setOpenid($data['openid']);

        $sender = new Sender($this->getAccessTokenObject());
        try {
            $msgid = $sender->send($template);
        } catch (\Exception $e) {
            Log::info('互助单号:'.$data['orderNo'].'，'.$e->getMessage());
            return $e->getMessage();
        }
    }

    /**
     * 邀请好友成功加入计划通知
     * @param $data
     * @return string
     */
    public function inviteUserPrompt($data) {
        $content = "您的好友". $data['userName'] .'已经成功加入'. $data['projetName'] .'('. str_replace(['[',']'], '', $data['projetSubTitle']) .')。恭喜您获得'.config('inviteAmount')."元奖励请到我的互助进行查看。积福互助感恩您的付出\n";
        //微信模板提示
        $template = new Template(config('wechat_template.WechatTemplateMessageInvite'));

        // 模板参数，每一个模板 ID 都对应一组参数
        $template
            ->add('first',      $content)
            ->add('keyword1',   "邀请好友")
            ->add('keyword2',   "获得奖励")
            ->add('remark',     "\n点击下方详情，去“我的互助”查看福币详情", '#0000ff');
        // 跳转链接
        $template->setUrl(config('domain.domain') .url('user/user_relation_log'));
        // 发给谁
        $template->setOpenid($data['openid']);

        $sender = new Sender($this->getAccessTokenObject());
        try {
            $msgid = $sender->send($template);
            Log::info($msgid.':'. var_export($data,true));
        } catch (\Exception $e) {
            Log::info(var_export($data,true).'------'.$e->getMessage());
            return $e->getMessage();
        }
    }

    /**
     * 用户计划生效
     * @param $data
     * @return string
     */
    public function userProjetTakeEffectPrompt($data, $type='') {
        if ($type !== 'age') {
            $content = "您的{$data['projetName']}已度过观察期，计划正式生效！万一发生不幸，所有会员将一起为您均摊互助金。为持续享有计划权限，您需要保持账户余额不低于{$data['projetCushionAmount']}元。\n";
        } else {
            $content = "由于您的年龄已经超过{$data['oldProjetName']}的限制，系统已自动为您转到{$data['projetName']}。为持续享有计划权限，您需要保持账户余额不低于{$data['projetCushionAmount']}元。\n";
        }
        //微信模板提示
        $template = new Template(config('wechat_template.WechatTemplateMessageTakeEffect'));

        // 模板参数，每一个模板 ID 都对应一组参数
        $template
            ->add('first',      $content)
            ->add('keyword1',   $data['protectName'])
            ->add('keyword2',   $data['projetName'])
            ->add('keyword3',   date('Y年m月d日'))
            ->add('keyword4',   date('Y年m月d日', $data['createTime']))
            ->add('remark',     "\n点击下方详情，去“我的互助”查看凭证", '#0000ff');
        // 跳转链接
        $template->setUrl(config('domain.domain') .url('user/projet'));
        // 发给谁
        $template->setOpenid($data['openid']);

        $sender = new Sender($this->getAccessTokenObject());
        try {
            $msgid = $sender->send($template);
            Log::info($msgid.':'. var_export($data,true));
        } catch (\Exception $e) {
            Log::info(var_export($data,true).'------'.$e->getMessage());
            return $e->getMessage();
        }
    }

    /**
     * 余额不足
     * @param $data
     * @return string
     */
    public function notSufficientFundsPrompt($data) {
        $content = "因您的余额低于最低限制({$data['projetCushionAmount']}元)，为了延续您的计划权限，请及时充值余额。\n";
        //微信模板提示
        $template = new Template(config('wechat_template.WechatTemplateMessageNotSufficientFunds'));

        // 模板参数，每一个模板 ID 都对应一组参数
        $template
            ->add('first',      $content)
            ->add('keyword1',   $data['protectName'])
            ->add('keyword2',   $data['projetName'])
            ->add('keyword3',   sprintf('%s%s', $data['totalFunds'], '元'))
            ->add('remark',     "\n点此前往充值", '#0000ff');
        // 跳转链接
        $template->setUrl(config('domain.domain') .url('user/projet_recharge',['userProjetId'=>$data['userProjetId']]));
        // 发给谁
        $template->setOpenid($data['openid']);

        $sender = new Sender($this->getAccessTokenObject());
        try {
            $msgid = $sender->send($template);
            Log::info($msgid.':'. var_export($data,true));
        } catch (\Exception $e) {
            Log::info(var_export($data,true).'------'.$e->getMessage());
            return $e->getMessage();
        }
    }

    /**
     * 用户计划失效
     * @param $data
     * @return string
     */
    public function userProjetLoseEfficacyPrompt($data, $type='') {
        if ($type === 'age') {
            $content = "因年龄超出限制，您的计划已失效。\n";
            $reason = "年龄高于{$data['maxAge']}岁，根据协议规定，自动失去计划权限";
        } else {
            $content = "因余额低于{$data['projetCushionAmount']}元，您的计划已失效。\n";
            $reason = "进入缓冲期后{$data['projetCushionTime']}天未对余额进行充值，根据协议规定，自动失去计划权限";
        }
        //微信模板提示
        $template = new Template(config('wechat_template.WechatTemplateMessageLoseEfficacy'));

        // 模板参数，每一个模板 ID 都对应一组参数
        $template
            ->add('first',      $content)
            ->add('keyword1',   $data['protectName'])
            ->add('keyword2',   $data['projetName'])
            ->add('keyword3',   $reason)
            ->add('keyword4',   date('Y年m月d日'))
            ->add('remark',     "\n点此查看计划凭证，欢迎重新加入计划", '#0000ff');
        // 跳转链接
        $template->setUrl(config('domain.domain') .url('user/projet'));
        // 发给谁
        $template->setOpenid($data['openid']);

        $sender = new Sender($this->getAccessTokenObject());
        try {
            $msgid = $sender->send($template);
            Log::info($msgid.':'. var_export($data,true));
        } catch (\Exception $e) {
            Log::info(var_export($data,true).'------'.$e->getMessage());
            return $e->getMessage();
        }
    }

    /**
     * 事件扣款通知
     * @param $data
     * @return string
     */
    public function mutualEventDeductionsPrompt($data) {
        $content = "事件扣款通知。\n";
        //微信模板提示
        $template = new Template(config('wechat_template.WechatTemplateMessageLoseEfficacy'));

        // 模板参数，每一个模板 ID 都对应一组参数
        $template
            ->add('first',      $content)
            ->add('keyword1',   $data['protectName'])
            ->add('keyword2',   $data['projetName'])
            ->add('keyword3',   $data['actualDeductionsAmount'])
            ->add('keyword4',   $data['userNum'])
            ->add('keyword5',   $data['actualMutualAmount'])
            ->add('remark',     "\n点此查看互助事件公示", '#0000ff');
        // 跳转链接
        $template->setUrl(config('domain.domain') .url('projet/publicity'));
        // 发给谁
        $template->setOpenid($data['openid']);

        $sender = new Sender($this->getAccessTokenObject());
        try {
            $msgid = $sender->send($template);
            Log::info($msgid.':'. var_export($data,true));
        } catch (\Exception $e) {
            Log::info(var_export($data,true).'------'.$e->getMessage());
            return $e->getMessage();
        }
    }
}